package controllers

import (
	//"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"kukukaki/models"
	"kukukaki/util"
	"path"
	"strings"
	"time"
	"unicode"
)

type SearchController struct {
	beego.Controller
}

type result struct {
	Result     int                     `json:"result"`
	Ingredient []models.IngredientInfo `json:"ii"`
	Language   string                  `json:"language"`
	Err        string                  `json:"err"`
}

func (c *SearchController) Show() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func IsChineseChar(str string) bool {
	for _, r := range str {
		if unicode.Is(unicode.Scripts["Han"], r) {
			return true
		}
	}
	return false
}

func IsJapaneseChar(str string) bool {
	for _, r := range str {
		if unicode.Is(unicode.Scripts["Katakana"], r) {
			return true
		}
	}
	return false
}

func IIsort(datalist *[]models.IngredientInfo, ii *[]string, lang *string) {
	result := []models.IngredientInfo{} // 存放结果
	index := 0

	if *lang == "cn" {

		for i := range *ii {
			//flag := false
			for j := range *datalist {
				if (*ii)[i] == (*datalist)[j].NameCN {
					//flag = true  // 存在重复元素，标识为false
					index = index + 1

					result = append(result, (*datalist)[j])
					break
				}
			}

		}

		*datalist = result

	} else if *lang == "en" {
		for i := range *ii {
			//flag := false
			for j := range *datalist {
				if (*ii)[i] == (*datalist)[j].INCI {
					//flag = true  // 存在重复元素，标识为false
					index = index + 1

					result = append(result, (*datalist)[j])
					break
				}
			}

		}

		*datalist = result
	} else if *lang == "jp" {
		for i := range *ii {
			//flag := false
			for j := range *datalist {
				if (*ii)[i] == (*datalist)[j].NameJP {
					//flag = true  // 存在重复元素，标识为false
					index = index + 1

					result = append(result, (*datalist)[j])
					break
				}
			}

		}

		*datalist = result
	}

}

//上传文件
func (this *SearchController) Ocr() {
	session := this.GetSession("user")
	var ret result

	if session == nil {
		ret = result{Err: "login"}
	} else {
		file, information, err := this.GetFile("image")

		if err != nil {
			this.Ctx.WriteString("File retrieval failure")
			ret = result{Err: "File retrieval failure"}
		} else {

			//得到文件的名称
			filename := information.Filename
			picture := strings.Split(filename, ".")

			//读取到字符串，并以.符号分隔开
			layout := strings.ToLower(picture[len(picture)-1])
			//把字母字符转换成小写，非字母字符不做出处理,返回此字符串转换为小写形式的副本。

			if layout != "jpg" && layout != "png" && layout != "gif" {
				//this.Ctx.WriteString("请上传符合格式的图片（png、jpg、gif）")
				//结束整个程序，不执行保存文件
				ret = result{Err: "请上传符合格式的图片（png、jpg、gif）"}
			} else {
				this.SaveToFile("image", path.Join("static/uploadfile", filename))

				img, err := ioutil.ReadAll(file)
				defer file.Close()
				if err != nil {
					ret = result{Err: err.Error()}
				} else {

					//fmt.Println(len(img))
					str, err := util.BaiduOCR(img)
					if err != nil {
						ret = result{Err: err.Error()}
					} else {
						//中英日 判断
						//分词https://github.com/go-ego/gse
						
						lang := "jp"
						if IsJapaneseChar(str)  == true {
							lang = "jp"
						} else if IsChineseChar(str) == true {
							lang = "cn"
							str = strings.ToUpper(str)
							index :=strings.Index(str, "成分")
							//beego.Info(index)
							if index >= 0 {
								str = str[index : len(str)-1]
							}
							
						} else {
							lang = "en"
						}
						beego.Info(lang)
						beego.Info(str)
						//获取分词结果
						ingredient := util.GetIngredients(&str, &lang) //util.GetIngredient(&str)
						beego.Info(ingredient)
						var list []models.IngredientInfo

						//带入数据库查询
						list, err = models.FindIIForName(&ingredient, &lang)
						//排序
						IIsort(&list,&ingredient,&lang)
						
						//beego.Info(list)
						if err != nil {
							ret = result{Err: err.Error()}
						} else {
							//ret = result{Content: str, Result: 1}
							us := session.(UserSession)
							us.UseNum = us.UseNum + 1
							us.WarningNum = us.WarningNum + len(list)
							us.UseAmount = us.UseAmount - 1

							models.SysCache.UpdateTime = time.Now().Format("2006-1-2 15:04:05")
							models.SysCache.AllUseNum = models.SysCache.AllUseNum + 1
							models.SysCache.AllWarningNum = models.SysCache.AllWarningNum + len(list)
							models.UpdateSysInfo()

							this.SetSession("user", us) //设置session
							
							u := models.UserInfo{Openid: us.Openid, UseNumber: us.UseNum, RiskWarningNumber: us.WarningNum, TheDayUseAmount: us.UseAmount}
							
							//存数据
							models.UpdateUserUse(&u)

							ret = result{Ingredient: list, Result: 1, Language: lang}

						}

					}

					//fmt.Println("---", str)

				}

			}

		}
	}

	this.Data["json"] = &ret
	this.ServeJSON()
	return
}
